<template>
  <Modal
    :open="visible"
    :title="modalTitle"
    width="1000px"
    @cancel="handleCancel"
    @ok="handleSubmit"
    :confirm-loading="submitLoading"
  >
    <Form />
  </Modal>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import { Modal, message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import { useFormSchema } from '../data';
import {
  createResource,
  updateResource,
  getResourceCategories,
  getResources,
} from '#/api/resource-center';

// Props
interface Props {
  visible: boolean;
  resourceData?: any;
  categoryId?: number;
  parentResourceId?: number; // 新增：父级资源ID
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  resourceData: null,
  categoryId: undefined,
  parentResourceId: undefined,
});

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean];
  success: [];
}>();

// 响应式数据
const submitLoading = ref(false);
const categoryTreeData = ref<any[]>([]);
const parentResourceTreeData = ref<any[]>([]);

// 表单相关
const [Form, formApi] = useVbenForm({
  schema: useFormSchema().map((item) => {
    if (item.field === 'category_id') {
      return {
        ...item,
        componentProps: {
          ...item.componentProps,
          treeData: categoryTreeData.value,
        },
      };
    }
    return item;
  }),
  showDefaultActions: false,
});

// 加载分类数据
const loadCategories = async () => {
  try {
    const response = await getResourceCategories();
    categoryTreeData.value = response?.items || [];
  } catch (error) {
    console.error('Load categories error:', error);
  }
};

// 加载父级资源数据
const loadParentResources = async () => {
  try {
    const response = await getResources({ pageSize: 1000 });
    const resources = response?.items || [];
    // 构建完整的资源树，允许所有资源作为父级
    const buildResourceTree = (
      parentId: number | null = null,
      level: number = 0,
    ): any[] => {
      return resources
        .filter((r: any) => r.parent_id === parentId)
        .map((r: any) => ({
          id: r.id,
          name: `${r.name} (${r.resource_type_name || r.resource_type})`,
          children: buildResourceTree(r.id, level + 1),
        }));
    };

    parentResourceTreeData.value = buildResourceTree();
  } catch (error) {
    console.error('Load parent resources error:', error);
  }
};

// 计算属性
const modalTitle = computed(() => {
  return props.resourceData ? '编辑资源' : '新建资源';
});

// 监听数据变化
watch(
  () => props.resourceData,
  (newData) => {
    if (newData) {
      formApi.setValues(newData);
    } else {
      formApi.setValues({});
    }
  },
  { immediate: true },
);

// 监听visible变化，加载分类数据
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      loadCategories();
      loadParentResources();
    }
  },
  { immediate: true },
);

// 监听分类数据变化，更新表单schema
watch(
  categoryTreeData,
  (newTreeData) => {
    if (newTreeData.length > 0) {
      formApi.updateSchema([
        {
          field: 'category_id',
          componentProps: {
            treeData: newTreeData,
          },
        },
      ]);
    }
  },
  { deep: true },
);

// 监听父级资源数据变化，更新表单schema
watch(
  parentResourceTreeData,
  (newTreeData) => {
    if (newTreeData.length > 0) {
      formApi.updateSchema([
        {
          field: 'parent_id',
          componentProps: {
            treeData: newTreeData,
          },
        },
      ]);
    }
  },
  { deep: true },
);

// 监听分类ID变化
watch(
  () => props.categoryId,
  (newCategoryId) => {
    if (newCategoryId && !props.resourceData) {
      formApi.setValues({ category_id: newCategoryId });
    }
  },
  { immediate: true },
);

// 监听父级资源ID变化
watch(
  () => props.parentResourceId,
  (newParentResourceId) => {
    if (newParentResourceId && !props.resourceData) {
      formApi.setValues({ parent_id: newParentResourceId });
    }
  },
  { immediate: true },
);

// 方法
const handleCancel = () => {
  emit('update:visible', false);
  formApi.setValues({});
};

const handleSubmit = async () => {
  try {
    const { valid } = await formApi.validate();
    if (!valid) return;
    const values = await formApi.getValues();
    submitLoading.value = true;

    // 处理JSON字段
    if (values.properties && typeof values.properties === 'string') {
      try {
        values.properties = JSON.parse(values.properties);
      } catch (error) {
        message.error('属性配置JSON格式错误');
        return;
      }
    }

    if (values.capabilities && typeof values.capabilities === 'string') {
      try {
        values.capabilities = JSON.parse(values.capabilities);
      } catch (error) {
        message.error('能力配置JSON格式错误');
        return;
      }
    }

    if (values.constraints && typeof values.constraints === 'string') {
      try {
        values.constraints = JSON.parse(values.constraints);
      } catch (error) {
        message.error('约束配置JSON格式错误');
        return;
      }
    }

    if (props.resourceData) {
      // 编辑
      await updateResource(props.resourceData.id, values);
      message.success('资源更新成功');
    } else {
      // 新建
      await createResource(values);
      message.success('资源创建成功');
    }

    emit('success');
  } catch (error) {
    console.error('Submit resource error:', error);
    message.error('操作失败');
  } finally {
    submitLoading.value = false;
  }
};
</script>

<style lang="less" scoped>
:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-form-item-label) {
  font-weight: 500;
}
</style>
